#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
from exception import RequestError
from request import http
from logger import logger


class Api:

    def __init__(self, repo=None, owner=None, token=None) -> None:
        self._repo = repo
        self._owner = owner
        self.token = token

    def _set_token(self):
        parameters = {"access_token": self.token} if self.token else {}
        return parameters

    @staticmethod
    async def _post(url, values, **kwargs):
        """
        POST into gitee API
        """
        try:
            response = await http.post(url=url, data=values, **kwargs)
        except RequestError as errors:
            logger.error(f'Call url {url} failed, message: {errors.message}')
            return None

        if not response.success:
            logger.warning("reuqest url: %s status code: %s error info: %s"
                           % (url, response.status_code, response.error))
            return None

        return response.json

    def set_attr(self, owner, repo):
        self._repo = repo
        self._owner = owner

    @staticmethod
    async def _get(url, params=None, text=False, **kwargs):
        """
        GET from gitee api
        """
        try:
            response = await http.get(url=url, params=params, **kwargs)
        except RequestError as errors:
            logger.error(f'Call url {url} failed, message: {errors.message}')
            return None

        if not response.success:
            logger.warning("reuqest url: %s status code: %s error info: %s"
                           % (url, response.status_code, response.error))
            return None

        return response.text if text else response.json
